package developerworks.jetty6;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Inbox {

	
	public String name;
	public String id;
	
	public String session_id;
	public String location;
	public String call_id;
	
	public String page;
	private Hashtable<String, Hashtable<String, Collection<CrudMessage>>> objects;


	public User user;
	
	public Inbox( HttpServletRequest req, HttpSession s , User u) {
		super();
		page = req.getHeader("Referer");
		call_id = req.getParameter("user[call_id]");
		objects = new Hashtable<String, Hashtable<String, Collection<CrudMessage>>>();
		user = u;
	}
	public String domain(){
		return ApplicationAddressBook.getDomainName(page);
	}
	
	public void addObject(CrudMessage o){
		
		String name =  o.getClass().getSimpleName();
		String status = o.getStatus();
		//synchronized(this) {
			Hashtable hash = (Hashtable) objects.get(name);
		    
			if(hash == null) {
		        hash = new Hashtable<String, Collection<CrudMessage>>();
		        objects.put(name, hash);
		    }
			Collection<CrudMessage> kinds = (Collection<CrudMessage>) hash.get(status);
			if(kinds == null){
				kinds = new ArrayList<CrudMessage>();
				hash.put(status, kinds);
			}
			kinds.add(o);
		//}
	}

	/**
	 * @return
	 */
	public String getMessages()  throws JSONException  {
		JSONObject classes = new JSONObject();
		String info = "";
		synchronized(this) {  //might not be needed b/c there is only one session that should ever grab this
			if(objects.isEmpty()) return "null";

			for(Enumeration<String> e = objects.keys(); e.hasMoreElements() ;){
				
				String name = e.nextElement();
				Hashtable<String, Collection<CrudMessage>> hash = (Hashtable<String, Collection<CrudMessage>>) objects.get(name);
				info += " "+name;
				
				//if(hash.isEmpty())
				//	System.out.println("Something is missing in "+name);
				
				JSONObject events = new JSONObject();
				for(Enumeration<String> hash_e = hash.keys(); hash_e.hasMoreElements() ;){
					String status = hash_e.nextElement();
					
					Collection<CrudMessage> kinds = (Collection<CrudMessage>) hash.get(status);
					
					info+= "{"+status+":"+kinds.size()+"}";
					JSONArray kind_array = new JSONArray();
					
					for(CrudMessage o : kinds){
						kind_array.put(o.toJson());
					}
					
					events.put(status, kind_array);
	
					kinds.clear();
				}
				info+= " ";
				classes.put(name, events);
	
				hash.clear();
			}
			objects.clear();
		}
		System.out.println("     sending  :"+info);
		return classes.toString();
	}
	
}
